#!/usr/bin/env python
from __future__ import with_statement
"""

    rtf_from_multiple_codon_alignment.py
    [--log_file PATH]
    [--quiet]

"""

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   options        


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

from optparse import OptionParser
import sys, os
import os.path
import StringIO

# add self to search path for testing
if __name__ == '__main__':
    exe_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
    sys.path.append(os.path.abspath(os.path.join(exe_path,"..", "python_modules")))
    module_name = os.path.split(sys.argv[0])[1]
    module_name = os.path.splitext(module_name)[0];
else:
    module_name = __name__

from general_util import die_error
from custom_log import custom_log



parser = OptionParser(version="%prog 1.0")
parser.add_option("-v", "--verbose", dest = "verbose",
                  action="store_true", default=False,
                  help="Do not echo to shell but only print to log.")
parser.add_option("-L", "--log_file", dest="log_file",
                  metavar="FILE", 
                  type="string",
                  help="name and path of log file")
parser.add_option("-d", "--data_file", dest="data_file",
                  metavar="FILE", 
                  type="string",
                  help="name and path of data file")
parser.add_option("--log_parameters", dest="log_parameters",
                    action="store_true", default=False,
                    help="Print program parameters to log.")

parameters = [  
                "log_file",
                ]

mandatory_parameters = []

# parameters default to none
for parameter in parameters:
    parser.set_defaults(**{parameter: None}) 

parser.set_defaults(log_file   = os.path.join(exe_path, "test", "codons_to_rtf.log"))
parser.set_defaults(data_file  = os.path.join(exe_path, "test", "test.multiple_alignment"))


# get help string
f =StringIO.StringIO()
parser.print_help(f)
helpstr = f.getvalue()
(options, remaining_args) = parser.parse_args()

# mandatory options
for parameter in mandatory_parameters:
    if options.__dict__[parameter] == None:
        die_error("Please specify a file in --%s.\n\n" % parameter + helpstr)





#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   imports        


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

import StringIO
import re
import operator

import general_util
from general_util import die_error
from collections import defaultdict
import get_command_line
from itertools import izip, count, groupby


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Functions        


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
def cnt_variants_by_pos (dna):
    variant_cnts_by_pos = list()
    for l in izip(*dna):
        cnt_nuc, nuc = sorted(((len(list(g)), k) for k, g in groupby(sorted(l))), reverse=True)[0]
        if cnt_nuc >= len(dna) - 1:
            variant_cnts_by_pos.append([1, nuc])
        else:
            variant_cnts_by_pos.append([0, nuc])
    return variant_cnts_by_pos
def read_dna ():
    dna = list()
    with open(options.data_file) as data:
        for line in data:
            dna.append(list(line.rstrip()))
    return dna

def write_rtf_header (output):
    output.write("\r\n".join(
        (r"{\rtf1\adeflang1025\ansi\ansicpg1252\uc1\adeff31507"
         r"\deff0\stshfdbch31506\stshfloch31506"
         r"\stshfhich31506\stshfbi31507\deflang2057\deflangfe2057"
         r"\themelang2057\themelangfe0\themelangcs0",
         r"{\fonttbl{\f2\fbidi \fmodern\fcharset0\fprq1 Courier New;}}",
         r"{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;"
         r"\red0\green255\blue0;\red255\green0\blue255;\red255\green0\blue0;"
         r"\red255\green255\blue0;\red255\green255\blue255;\red0\green0\blue128;"
         r"\red0\green128\blue128;\red0\green128\blue0;\red128\green0\blue128;"
         r"\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;"
         r"\red192\green192\blue192;"
         r"\cbackgroundone\ctint255\cshade255\red255\green255\blue255;}",
         r"{\*\xmlnstbl {\xmlns1 http://schemas.microsoft.com/office/word/2003/wordml}}"
         r"\paperw16838\paperh11906\margl1440\margr1440\margt1440\margb1440\f2")) + "\r\n")

def write_rtf_tail (output):
    output.write("}")

        
#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Main logic


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

from custom_log import custom_log
logger = custom_log(module_name, options.log_file)

if options.log_parameters:
    save_option_parameters (logger)

    
dna = read_dna()

variant_cnts_by_pos = cnt_variants_by_pos(dna)
                

write_rtf_header (sys.stdout)

for align in dna:
    prev_code = ""
    prev_nuc = ""
    for pos, (highlight, match_nuc), nuc in izip(count(), variant_cnts_by_pos, align):
        code = ""
        if highlight and match_nuc == nuc:
            code = r"\cf17\highlight1\b"
        #if pos %3 == 2:
        #    code += r"\expnd4\expndtw20"
        if len(code):
            code += " "
        if len(prev_nuc):
            if code != prev_code:
                sys.stdout.write("{%s%s}" % (prev_code, prev_nuc))
                prev_nuc = ""
        prev_nuc += nuc
        prev_code = code
        if pos %3 == 2:
            sys.stdout.write("{%s%s}{\\afs8  }" % (prev_code, prev_nuc))
            prev_nuc = ""
            
    sys.stdout.write("\\par\r\n")
write_rtf_tail(sys.stdout)    
